const ffmpeg = require('fluent-ffmpeg');
const fs = require('fs');
const path = require('path');
const crypto = require('crypto');
const config = require('./config.js');
const videoType = config.videoType;
const imgType = config.imgType;
const imgsPath = path.join(__dirname, 'public', 'thumbnails');
const exec = require("child_process").exec;
const isDirectory = ['D盘', 'E迅雷云盘', 'F盘下载', 'G盘下载', 'H盘下载'];

if (!fs.existsSync('./videoToImg.json')) fs.writeFileSync('./videoToImg.json', '{}');
let videoToImg = require('./videoToImg.json');

async function deleteDir(){
  return new Promise((resolve, reject) => {
    exec(`rd /q /s ${imgsPath}`, {}, function(err, stdout, stderr) {
      if (err) reject(err);
      resolve();
    });
  })
};

!async function generateThumbnails(dir, noDeleteFlag){
  // 先判断缩略图目录是否存在，如果存在则删掉，然后创建，全量更新
  if (noDeleteFlag) {
    if (fs.existsSync(imgsPath)) {
      await deleteDir();
      fs.unlinkSync('./videoToImg.json');
    }
    videoToImg = {};
    fs.mkdirSync(imgsPath);
    fs.writeFileSync(`${imgsPath}/Movies.png`, fs.readFileSync('./Movies.png'));
    fs.writeFileSync(`${imgsPath}/unknown.png`, fs.readFileSync('./unknown.png'));
  }
  // 遍历public目录下的文件
  const videoList = fs.readdirSync(dir);
  for (let video of videoList) {
    if (config.skipDirectory.includes(video) || video.startsWith('.')) continue;
    const videoNameArr = video.split('.');
    // 如果是一个目录的话，则递归调用
    if (videoNameArr.length === 1) {
      const stat = fs.lstatSync(`${dir}/${video}`);
      if (stat.isDirectory() || isDirectory.includes(video)) await generateThumbnails(`${dir}/${video}`, false);
    }
    // [ '空姐', 'mp4' ]
    // suffix取最后一个元素，判断是不是视频类型
    const suffix = videoNameArr[videoNameArr.length - 1];
    if (videoNameArr.length != 1 && videoType.includes(suffix.toLocaleLowerCase()) || imgType.includes(suffix.toLocaleLowerCase())) {
      // videoToImg对象主要负责记录这个视频文件对应的缩略图。
      // 如果public目录下有个叫a.mp4的，子目录下也有个叫a.mp4的，不会出现缩略图名字被覆盖的情况
      const relativePath = dir.substring(dir.indexOf('public') + 6, dir.length);
      const hash = crypto.createHash('md5').update(`${relativePath}/${video}`).digest('hex');
      // 增量更新，如果存在就跳过
      if (videoToImg[`${relativePath}/${video}`]) continue;
      videoToImg[`${relativePath}/${video}`] = `thumbnails/${hash}.png`.replace(/ /g, '');
      if (imgType.includes(suffix.toLocaleLowerCase())) {
        console.log(video)
        continue;
      }
      // 如果没有生成视频的缩略图说明视频太短，没有到38秒
      await new Promise(function (resolve){
        new ffmpeg(`${dir}/${video}`).screenshots({
          timemarks: ['38'],
          count: 1,
          filename: hash,
          folder: imgsPath,
          size: '320x240'
        }).on('end', function() {
          console.log(video);
          resolve();
        });
      });
    }
  }
fs.writeFileSync('./videoToImg.json', JSON.stringify(videoToImg))

}(path.join(__dirname, 'public'), false)